package org.example.ymcc.consumer;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.example.ymcc.constant.Constants;
import org.example.ymcc.constant.MQConstants;

import org.example.ymcc.constant.RConst;
import org.example.ymcc.domain.CourseOrder;
import org.example.ymcc.domain.PayOrder;
import org.example.ymcc.dto.OrderPayDto;
import org.example.ymcc.mapper.PayOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "PayConsumer",
        topic = MQConstants.MQ_PAY_ORDER_TOPIC,
        selectorExpression = MQConstants.MQ_PAY_ORDER_TAG
)
public class PayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private PayOrderMapper payOrderMapper;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String s = new String(body, Constants.UTF8);
            OrderPayDto dto = JSONObject.parseObject(s, OrderPayDto.class);
            //保存payOrder
            PayOrder payOrder = new PayOrder();
            payOrder.setCreateTime(new Date());
            payOrder.setAmount(dto.getPayAmount());
            payOrder.setPayType(dto.getPayType());
            payOrder.setRelationId(dto.getCourseIds());
            payOrder.setOrderNo(dto.getOrderNo());
            payOrder.setUserId(dto.getUserId());
            payOrder.setSubject(dto.getTitle());
            payOrder.setPayStatus(RConst.Num.INT_0);
            payOrderMapper.insert(payOrder);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
